package xdu.lz.stage6_threadpool.chapter3_threadPoolExecutorAPI;


import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * Created at 2019/10/24 0024 下午 5:55
 * 比如：要采集100条数据，开启了200个线程，只要前100个采集完毕后，就把计划给取消。
 * 运气不好的话 ，getResult的时候可能拿的是最耗时间的那个。
 * <p>
 * 见{@link ExecutorCompletionService}，内置了一个BlockingQueue，会把先执行完的结果放到queue中，
 * 测试见
 */
public class ExecutorCompletionServiceDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test();
    }

    private static void test() throws InterruptedException, ExecutionException {
        ExecutorService excutor = Executors.newFixedThreadPool(5);
        ExecutorCompletionService<Integer> service = new ExecutorCompletionService<>(excutor);
        List<Callable<Integer>> tasks = new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            final int finalI = i;
            Callable<Integer> callable = new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    Thread.sleep(finalI * 50);
                    return finalI;
                }
            };
            tasks.add(callable);
        }

        List<Future<Integer>> futures = new ArrayList<>();
        tasks.stream().forEach(task -> futures.add(service.submit(task)));

        Future future;
        //take会阻塞，put也会阻塞
        while ((future = service.take()) != null) {
            System.out.println(future.get());
        }

        //其他非阻塞API
        service.poll();
        service.poll(10,TimeUnit.SECONDS);

    }
}
